const createError = require("http-errors");
const express = require("express");
const cors = require("cors");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const ApiError = require("../common/api-errors");
const {
  restfulMiddleware,
  errorHandler,
} = require("../middlewares/restful-api-middleware");

const indexRouter = require("../routes/index");

const app = express();
app.disable("x-powered-by");

app.use(
  cors({
    methods: ["GET", "POST"],
  })
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(restfulMiddleware);

app.use("/", indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.sendPacket(ApiError.NOT_FOUND);
});

// error handler
app.use(errorHandler);

module.exports = app;
